<template>
    <div class="JADP-common-layout">
      <div class="JADP-common-layout-center">
        <el-row class="JADP-common-search-box" :gutter="16">
          <el-form @submit.native.prevent>
            <el-col :span="6">
              <el-form-item label="培训类别">
                <el-select
                  v-model="query.traintype"
                  placeholder="请选择"
                  clearable
                >
                  <el-option
                    v-for="(item, index) in getDict('pxlb')"
                    :key="index"
                    :label="item.dataName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="培训行业">
                <el-select
                  v-model="query.categorytype"
                  placeholder="请选择"
                  clearable
                >
                  <el-option
                    v-for="(item, index) in getDict('hangye')"
                    :key="index"
                    :label="item.dataName"
                    :value="item.id"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="学员姓名">
                <el-input v-model="query.realname" placeholder="请输入" clearable>
                </el-input>
              </el-form-item>
            </el-col>
  
            <template v-if="showAll">
              <el-col :span="6">
                <el-form-item label="班级名称">
                  <el-input
                    v-model="query.classname"
                    placeholder="请输入"
                    clearable
                  >
                  </el-input>
                </el-form-item>
              </el-col>
  
              <el-col :span="6">
                <el-form-item label="发票状态">
                  <el-select v-model="query.invoicestatus">
                    <el-option
                      v-for="(item, index) in getDict('fpzt')"
                      :key="index"
                      :label="item.dataName"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
  
              <el-col :span="6">
                <el-form-item label="税号">
                  <el-input
                    v-model="query.dutyparagraph"
                    placeholder="请输入"
                    clearable
                  >
                  </el-input>
                </el-form-item>
              </el-col>
  
              <el-col :span="6">
                <el-form-item label="发票抬头">
                  <el-input
                    v-model="query.invoicetitle"
                    placeholder="请输入"
                    clearable
                  >
                  </el-input>
                </el-form-item>
              </el-col>
              <!-- <el-col :span="6">
                <el-form-item label="订单号">
                  <el-input
                    v-model="query.orderno"
                    placeholder="请输入单位名称"
                    clearable
                  >
                  </el-input>
                </el-form-item>
              </el-col> -->
            </template>
            <el-col :span="6">
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="search()"
                  >查询</el-button
                >
                <el-button icon="el-icon-refresh-right" @click="reset()"
                  >重置</el-button
                >
                <el-button
                  type="text"
                  icon="el-icon-arrow-down"
                  @click="showAll = true"
                  v-if="!showAll"
                >
                  展开
                </el-button>
                <el-button
                  type="text"
                  icon="el-icon-arrow-up"
                  @click="showAll = false"
                  v-else
                >
                  收起
                </el-button>
              </el-form-item>
            </el-col>
          </el-form>
        </el-row>
        <div class="JADP-common-layout-main JADP-flex-main">
          <div class="JADP-common-head">
            <div>
              <el-button
                type="text"
                icon="el-icon-download"
                @click="exportData(1)"
                >导出订单
              </el-button>
              <!-- <el-button
                type="text"
                icon="el-icon-delete"
                @click="handleBatchRemoveDel()"
                >批量删除
              </el-button> -->
              <el-button
                type="text"
                icon="el-icon-download"
                @click="exportData(2)"
                >导出发票
              </el-button>
              <el-button
                type="text"
                icon="el-icon-document"
                @click="batchInvoices()"
                >批量开票
              </el-button>
            </div>
            <div class="JADP-common-head-right">
              <el-tooltip effect="dark" content="刷新" placement="top">
                <el-link
                  icon="icon-ym icon-ym-Refresh JADP-common-head-icon"
                  :underline="false"
                  @click="reset()"
                />
              </el-tooltip>
              <screenfull :isContainer="true" />
              <!-- <el-tooltip effect="dark" content="列设置" placement="top">
                <el-link
                  icon="icon-ym icon-ym-options JADP-common-head-icon"
                  :underline="false"
                />
              </el-tooltip> -->
            </div>
          </div>
          <el-table
            v-loading="listLoading"
            :data="list"
            @sort-change="sortChange"
            ref="table"
            border
            class="JADP-common-table"
            @selection-change="handleSelectionChange"
            height="100%"
          >
            <el-table-column
              type="selection"
              width="55"
              :selectable="selectable"
            />
            <el-table-column type="index" label="序号" width="50" />
            <el-table-column
              prop="orderno"
              label="订单号"
              align="center"
              width="100"
              show-overflow-tooltip
            />
            <el-table-column
              prop="studentsEntity.invoicetitle"
              label="发票抬头"
              align="center"
              width="100"
              show-overflow-tooltip
            />
            <el-table-column
              prop="studentsEntity.dutyparagraph"
              label="税号"
              align="center"
              width="100"
              show-overflow-tooltip
            />
  
            <el-table-column
              prop="realname"
              label="学员"
              align="center"
              width="90"
            >
              <template #default="{ row }">
                {{ row.studentsEntity.realname }}
              </template>
            </el-table-column>
            <el-table-column
              prop="classInfoEntity.classname"
              label="班级名称"
              align="center"
              show-overflow-tooltip
            />
  
            <el-table-column
              prop="trainType"
              label="培训类别"
              align="center"
              width="150"
              show-overflow-tooltip
  
            >
              <template #default="{ row }">
                {{ getDict("pxlb", row.classInfoEntity.trainType) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="categorytype"
              label="培训行业"
              align="center"
              width="130"
            >
              <template #default="{ row }">
                {{ getDict("hangye", row.classInfoEntity.categorytype) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="trainMode"
              label="培训类型"
              align="center"
              width="95"
            >
              <template #default="{ row }">
                {{ getDict("bjpxfs", row.classInfoEntity.trainMode) }}
              </template>
            </el-table-column>
            <el-table-column
              prop="traindateStart"
              label="培训开始"
              align="center"
              width="100"
            >
              <template #default="{ row }">
                {{
                  dayjs(row.classInfoEntity.traindateStart / 1).format(
                    "YYYY-MM-DD"
                  )
                }}
              </template>
            </el-table-column>
            <el-table-column
              prop="traindateEnd"
              label="培训截止"
              width="100"
              align="center"
            >
              <template v-slot="{ row }">
                {{
                  dayjs(row.classInfoEntity.traindateEnd / 1).format("YYYY-MM-DD")
                }}
              </template>
            </el-table-column>
            <el-table-column prop="accountstatus" label="价格" align="center">
              <template #default="{ row }">
                {{ row.classInfoEntity.traincharge }}
              </template>
            </el-table-column>
            <el-table-column
              prop="status"
              label="订单状态"
              align="center"
              width="150"
            >
              <template #default="{ row }">
                <el-tag
                  style="width: 125px"
                  :type="handlerStatus(row.orderstatus)"
                  >{{ row.orderstatus }}</el-tag
                >
              </template>
            </el-table-column>
            <el-table-column label="发票状态" width="85">
              <template #default="{ row }">
                {{
                  row.invoicestatus
                    ? getDict("fpzt", row.invoicestatus)
                    : row.invoicestatus
                }}
              </template>
            </el-table-column>
            <el-table-column
              prop="creatortime"
              label="报名时间"
              align="center"
              width="160"
            >
              <template #default="{ row }">
                {{
                  dayjs(row.classInfoEntity.creatortime / 1).format(
                    "YYYY-MM-DD HH:mm:ss"
                  )
                }}
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="180">
              <template #default="{ row }">
                <el-button
                  type="text"
                  @click="orderDetail(row.id, row.classInfoEntity.traincharge)"
                  >订单详情
                </el-button>
                <el-button
                  type="text"
                  v-if="row.orderstatus == '提交报名等待审核'"
                  @click="
                    examine(
                      row.studentsEntity.id,
                      row.id,
                      row.classInfoEntity.traincharge
                    )
                  "
                  >审核</el-button
                >
                <el-button
                  v-if="row.classInfoEntity.traincharge !== 0"
                  type="text"
                  @click="invoice(row.id)"
                  >发票
                </el-button>
                <el-button
                  type="text"
                  v-if="
                    row.orderstatus == '退款申请中' &&
                      userInfo.userId == 'admin' &&
                      row.refundstatus == 0
                  "
                  @click="refund(row)"
                  >退款审批
                </el-button>
                <el-button
                  type="text"
                  v-if="userInfo.userId == 'system' && row.refundstatus == 1"
                  @click="tuikuan(row)"
                  >退款
                </el-button>
                <!-- <el-button type="text" @click="addOrUpdateHandle(scope.row.id)"
                  >编辑
                </el-button> -->
              </template>
            </el-table-column>
          </el-table>
  
          <pagination
            :total="total"
            :page.sync="listQuery.currentPage"
            :limit.sync="listQuery.pageSize"
            @pagination="initData"
          />
        </div>
      </div>
      <ExportBox v-if="exportBoxVisible" ref="ExportBox" @download="download" />
      <ImportBox
        v-if="importBoxVisible"
        ref="importBox"
        @refresh="reset()"
        @ImportPreviewApi="ImportPreviewApi"
        @importDataApi="importDataApi"
        @TemplateDownload="TemplateDownload"
        :URL="URL"
      />
      <ResetPwdForm
        v-if="resetFormVisible"
        ref="ResetPwdForm"
        @refreshDataList="initData"
      />
      <Examine ref="examine" :visible.sync="examineVisible" @refresh="refresh" />
      <OrderDetail ref="orderDetail" :visible.sync="orderVisible" />
      <Invoice :visible.sync="invoiceVisible" ref="invoice" @refresh="refresh" />
      <BatchInvoice
        v-if="batchInvoiceVisible"
        ref="batchInvoice"
        @refresh="refresh"
      />
      <el-dialog
        title="退款审批"
        :visible.sync="dialogVisible"
        width="30%"
        class="JADP-dialog JADP-dialog_center"
      >
        <el-row>
          <el-col :span="4" style="padding-top:10px">退款原因：</el-col>
          <el-col :span="20" class="reason">{{ refundreson }}</el-col>
        </el-row>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible2 = true">不通过</el-button>
          <el-button type="primary" @click="refundExamine">通 过</el-button>
        </span>
      </el-dialog>
  
      <el-dialog
        title="退款审批备注"
        :visible.sync="dialogVisible2"
        width="30%"
        class="JADP-dialog JADP-dialog_center"
      >
        <el-form ref="form" :model="form" label-width="80px" :rules="rules">
          <el-form-item label="驳回原因" prop="refundremarks">
            <el-input type="textarea" v-model="form.refundremarks"></el-input>
          </el-form-item>
        </el-form>
  
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible2 = false">取 消</el-button>
          <el-button type="primary" @click="reject_">确 定</el-button>
        </span>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import request from "@/utils/request";
  import { mapGetters } from "vuex";
  import { getDictionaryDataSelector } from "@/api/systemData/dictionary";
  import Examine from "./examine.vue";
  import OrderDetail from "./orderDetail.vue";
  import BatchInvoice from "./batchInvoice.vue";
  import Invoice from "./invoice.vue";
  // import JADPForm from "./Form";
  // import ResetPwdForm from "./ResetPassword";
  // import { previewDataInterface } from "@/api/systemData/dataInterface";
  
  export default {
    name: "aaa",
    //   components: { JADPForm, ExportBox, ResetPwdForm },
    components: { Examine, OrderDetail, Invoice, BatchInvoice },
    data() {
      return {
        //导入属性
        importBoxVisible: false,
        orderVisible: false,
        URL: "students/Xy_ks_students",
        showAll: false,
        invoiceVisible: false,
        examineVisible: false,
        batchInvoiceVisible: false,
        query: {
          invoicestatus: undefined,
          dutyparagraph: undefined,
          invoicetitle: undefined,
          orderno: undefined,
          realname: undefined,
          classname: undefined,
          traintype: undefined,
          categorytype: undefined,
          orderstatus: undefined
        },
        defaultProps: {
          children: "children",
          label: "fullName"
        },
        list: [],
        listLoading: true,
        multipleSelection: [],
        multipleSelection1: [],
        total: 0,
        listQuery: {
          currentPage: 1,
          pageSize: 20,
          sort: "desc",
          sidx: "creatortime"
        },
        formVisible: false,
        exportType: "",
        resetFormVisible: false,
        exportBoxVisible: false,
        columnList: [
          { prop: "orderno", label: "订单号" },
          { prop: "invoicetitle", label: "发票抬头" },
          { prop: "dutyparagraph", label: "税号" },
          { prop: "realname", label: "学员" },
          { prop: "classname", label: "班级名称" },
          { prop: "trainType", label: "培训类别" },
          { prop: "categorytype", label: "培训行业" },
          { prop: "trainMode", label: "培训类型" },
          { prop: "traindateStart", label: "培训开始" },
          { prop: "traindateEnd", label: "培训截止" },
          { prop: "accountstatus", label: "价格" },
          { prop: "status", label: "订单状态" },
          { prop: "invoicestatus", label: "发票状态" },
          { prop: "creatortime", label: "报名时间" }
        ],
        columnList1: [
          { label: "配送方式", prop: "deliverymode" },
          { label: "发票状态", prop: "invoicestatus" },
          { label: "开票寄出时间", prop: "invoicingtime" },
          { label: "发票快递信息", prop: "invoiceinfo" },
          { label: "发票内容", prop: "invoicecontent" },
          { label: "发票抬头", prop: "invoicetitle" },
          { label: "税号", prop: "dutyparagraph" },
          { label: "单位地址", prop: "unitaddress" },
          { label: "电话号码", prop: "telephone" },
          { label: "开户银行", prop: "bank" },
          { label: "银行卡号", prop: "bankaccount" }
        ],
        dialogVisible: false,
        dialogVisible2: false,
        refundreson: "",
        refundId: "",
        form: {
          refundremarks: ""
        },
        rules: {
          refundremarks: [
            {
              required: true,
              message: "请输入驳回原因",
              trigger: "blur"
            }
          ]
        }
      };
    },
    computed: {
      handlerStatus() {
        return function(status) {
          let type;
          switch (status) {
            case "报名审核不通过":
              type = "danger";
              break;
            case "报名成功已完成付款":
              type = "success";
              break;
            case "提交报名等待审核":
              type = "warning";
              break;
            case "报名成功等待付款":
              type = "";
              break;
            case "退款申请中":
              type = "warning";
              break;
            case "退款成功":
              type = "success";
              break;
            case "退款失败":
              type = "danger";
              break;
            case "退款审核被驳回":
              type = "danger";
              break;
            case "退款审核通过":
              type = "success";
              break;
            default:
              type = "info";
          }
          return type;
        };
      },
      ...mapGetters(["userInfo"])
    },
    created() {
      if (
        this.$route.query.orderFlag &&
        JSON.parse(this.$route.query.orderFlag)
      ) {
        this.query.orderstatus = "提交报名等待审核";
      }
      this.initData();
    },
    methods: {
      selectable(row) {
        if (
          row.orderstatus == "报名成功已完成付款" &&
          row.classInfoEntity.traincharge !== 0
        ) {
          return true;
        } else {
          return false;
        }
      },
      invoice(id) {
        this.invoiceVisible = true;
        this.$refs.invoice.initData(id);
      },
      examine(id, orderId, price) {
        console.log(id, orderId, price, "id, orderId,price");
        this.examineVisible = true;
        this.$refs.examine.init(id, orderId, price);
      },
      batchInvoices() {
        if (!this.multipleSelection.length) {
          this.$message({
            type: "error",
            message: "请选择一条数据",
            duration: 1500
          });
          return;
        }
        let c = this.multipleSelection1.every(
          item =>
            item.studentsEntity.dutyparagraph ==
            this.multipleSelection1[0].studentsEntity.dutyparagraph
        );
        if (!c)
          return this.$message({
            type: "error",
            message: "请重新选择确保税号一致",
            duration: 800,
            onClose: () => this.$refs.table.$refs.JADPTable.clearSelection()
          });
        this.batchInvoiceVisible = true;
        this.$nextTick(() =>
          this.$refs.batchInvoice.init(this.multipleSelection1)
        );
      },
      orderDetail(id, price) {
        this.orderVisible = true;
        this.$refs.orderDetail.init(id, price);
      },
      ImportPreviewApi(val) {
        let query = { fileName: val };
        request({
          url: `/api/students/Xy_ks_students/ImportPreview`,
          method: "get",
          data: query
        })
          .then(res => {
            this.$refs.importBox.list = res.data.dataRow;
            this.$refs.importBox.btnLoading = false;
            this.$refs.importBox.active++;
          })
          .catch(() => {
            this.$refs.importBox.btnLoading = false;
          });
      },
      importDataApi(val) {
        let query = { list: val,organizeId :this.$store.getters.organizeId };
        request({
          url: `/api/students/Xy_ks_students/ImportData`,
          method: "post",
          data: query
        })
          .then(res => {
            this.$refs.importBox.result = res.data;
            this.$refs.importBox.resultList = res.data.failResult;
            this.$refs.importBox.btnLoading = false;
            this.$refs.importBox.active++;
          })
          .catch(() => {
            this.$refs.importBox.btnLoading = false;
          });
      },
      TemplateDownload() {
        request({
          url: `/api/students/Xy_ks_students/templateDownload`,
          method: "post"
        }).then(res => {
          if (!res.data.url) return;
          window.location.href = this.define.comUrl + res.data.url;
        });
      },
      uploadForm() {
        this.importBoxVisible = true;
        this.$nextTick(() => {
          this.$refs.importBox.init(this.columnList);
        });
      },
      sortChange({ column, prop, order }) {
        this.listQuery.sort = order == "ascending" ? "asc" : "desc";
        this.listQuery.sidx = !order ? "" : prop;
        this.initData();
      },
      initData() {
        this.listLoading = true;
        let _query = {
          ...this.listQuery,
          ...this.query,
          orderstatus:"提交报名等待审核",
          organizeId:this.$store.getters.organizeId
        };
        let query = {};
        for (let key in _query) {
          if (Array.isArray(_query[key])) {
            query[key] = _query[key].join();
          } else {
            query[key] = _query[key];
          }
        }
        request({
          url: `/api/orders/Xy_ks_orders`,
          method: "get",
          data: query
        }).then(res => {
          this.list = res.data.list;
          this.list.sort((a, b) => (a.creatortime < b.creatortime ? 1 : -1));
          this.total = res.data.pagination.total;
          this.listLoading = false;
        });
      },
      handleDel(id) {
        this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
          type: "warning"
        })
          .then(() => {
            request({
              url: `/api/students/Xy_ks_students/${id}`,
              method: "DELETE"
            }).then(res => {
              this.$message({
                type: "success",
                message: res.msg,
                onClose: () => {
                  this.initData();
                }
              });
            });
          })
          .catch(() => {});
      },
      handleSelectionChange(val) {
        console.log(val, "val");
        const res = val.map(item => item.id);
        this.multipleSelection = res;
        this.multipleSelection1 = val;
      },
      handleBatchRemoveDel() {
        if (!this.multipleSelection.length) {
          this.$message({
            type: "error",
            message: "请选择一条数据",
            duration: 1500
          });
          return;
        }
        const ids = this.multipleSelection.join();
        this.$confirm("您确定要删除这些数据吗, 是否继续？", "提示", {
          type: "warning"
        })
          .then(() => {
            request({
              url: `/api/students/Xy_ks_students/batchRemove/${ids}`,
              method: "DELETE"
            }).then(res => {
              this.$message({
                type: "success",
                message: res.msg,
                onClose: () => {
                  this.initData();
                }
              });
            });
          })
          .catch(() => {});
      },
      exportData(val) {
        this.exportType = val;
        let a = val == 1 ? this.columnList : this.columnList1;
        this.exportBoxVisible = true;
        this.$nextTick(() => {
          this.$refs.ExportBox.init(a);
        });
      },
      download(data) {
        let query = { ...data, ...this.listQuery, ...this.query };
        let url =
          // 1 导出订单 2 导出发票
          this.exportType == 1
            ? "/api/orders/Xy_ks_orders/Actions/Export"
            : "/api/orders/Xy_ks_orders/Actions/Export/Fp";
        request({
          url,
          method: "GET",
          data: query
        }).then(res => {
          if (!res.data.url) return;
          window.location.href = this.define.comUrl + res.data.url;
          this.$refs.ExportBox.visible = false;
          this.exportBoxVisible = false;
        });
      },
      search() {
        this.listQuery = {
          currentPage: 1,
          pageSize: 20,
          sort: "desc",
          sidx: "creatortime"
        };
        this.initData();
      },
      //退款审批
      refund(row) {
        this.dialogVisible = true;
        console.log(row);
        this.refundreson = row.refundreson;
        this.refundId = row.id;
      },
  
      //退款审核结果通过
      refundExamine() {
        request({
          url: "/api/orders/Xy_ks_orders/refundShenHe/" + this.refundId,
          method: "put",
          data: {
            refundstatus: 1,
            orderstatus: "退款审核通过"
          }
        }).then(res => {
          this.dialogVisible = false;
          this.initData();
        });
      },
      //退款
      tuikuan(value) {
        console.log(value);
        this.$confirm("你确定要进行退款吗？")
          .then(_ => {
            if (value.paytype == "微信") {
              if (value.tradetype == "JSAPI") {
                request({
                  url: "/v3/wxapplet/refund/" + value.orderno,
                  method: "post"
                }).then(res => {
                  this.initData();
                  this.$message.success(res.msg);
                  console.log(res, "微信小程序");
                });
              } else {
                request({
                  url: "/v3/wxpay/refund/" + value.orderno,
                  method: "post"
                }).then(res => {
                  this.initData();
                  this.$message.success(res.msg);
                  console.log(res, "微信");
                });
              }
            } else if (value.paytype == "支付宝") {
              request({
                url: "/v3/app/alipay/refund/" + value.orderno,
                method: "post"
              }).then(res => {
                // console.log(res, "支付宝");
                this.initData();
                this.$message.success(res.msg);
              });
            }
          })
          .catch(_ => {});
      },
  
      //退款审核结果不通过
      reject_() {
        request({
          url: "/api/orders/Xy_ks_orders/refundShenHe/" + this.refundId,
          method: "put",
          data: {
            refundstatus: 2,
            refundremarks: this.form.refundremarks,
            orderstatus: "退款审核被驳回"
          }
        }).then(res => {
          this.dialogVisible = false;
          this.dialogVisible2 = false;
          this.initData();
        });
      },
  
      refresh(isrRefresh) {
        this.batchInvoiceVisible = false;
        if (isrRefresh) this.reset();
      },
      reset() {
        for (let key in this.query) {
          this.query[key] = undefined;
        }
        if (
          this.$route.query.orderFlag &&
          JSON.parse(this.$route.query.orderFlag)
        ) {
          this.query.orderstatus = "提交报名等待审核";
        }
        this.listQuery = {
          currentPage: 1,
          pageSize: 20,
          sort: "desc",
          sidx: "creatortime"
        };
        this.initData();
      }
    }
  };
  </script>
  
  <style scoped lang="scss">
  .reason {
    min-height: 100px;
    border: 1px solid #ccc;
    padding: 10px;
  }
  </style>
  